package org.sakai.entity;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Map;

/**
 * 响应码枚举
 * @param <T>
 */
@Data
public class ApiResponseEntity<T> {
    @Schema(description = "响应码")
    private int code;
    @Schema(description = "响应码描述")
    private String message;
    @Schema(description = "数据")
    private T data;
    @Schema(description = "响应头")
    private Map<String, String> headers;

    public ApiResponseEntity(int code, T data){
        this.code = code;
        this.data = data;
    }

    public ApiResponseEntity(int code, String message, T data){
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public ApiResponseEntity(int code, T data, Map<String, String> headers){
        this.code = code;
        this.data = data;
        this.headers = headers;
    }

    public static <T> ResponseEntity ok(T data){
        ApiResponseEntity<T> tApiResponseEntity = new ApiResponseEntity<T>(HttpStatus.OK.value(), data);
        return tApiResponseEntity.getResponseEntity();
    }

    public static <T> ResponseEntity error(ErrorCode code){
        ApiResponseEntity<T> tApiResponseEntity = new ApiResponseEntity<T>(HttpStatus.INTERNAL_SERVER_ERROR.value(), code.toString(), null);
        return tApiResponseEntity.getResponseEntity();
    }
    public static <T> ResponseEntity getResponseEntity(Result<T> result){
        if(result.isSuccess()){return ApiResponseEntity.ok(result.getData());}
        return ApiResponseEntity.error(result.getErrorCode());
    }

    /**
     * 生成响应体
     * @return
     */
    public ResponseEntity<ApiResponseBody<T>> getResponseEntity(){
        HttpHeaders httpHeaders = new HttpHeaders();
        if(this.headers != null){
            for(Map.Entry<String,String> entry: this.headers.entrySet()){
                httpHeaders.add(entry.getKey(), entry.getValue());
            }
        }
        ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        return ResponseEntity
                .status(this.code)
                .headers(httpHeaders)
                .body(new ApiResponseBody<T>(this.message,this.data, zonedDateTime.toString()));
    }
}
